package com.cn.chaomeng.filter;

import com.cn.chaomeng.controller.AdminController;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author LYJ
 *         Created by Administrator on 2018/1/6 0006.
 */
public class AdminFilter extends OncePerRequestFilter
{

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException
    {

        // 请求的uri
        String uri = request.getRequestURI();
        // 不过滤的uri
        String[] notFilter = new String[] {"/admin/index", "/admin/login"};

        String type = request.getHeader("X-Requested-With");
        String path = request.getContextPath();
        String basePath =
            request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";

        // 是否过滤
        boolean doFilter = true;
        for (String s : notFilter)
        {
            if (uri.contains(s))
            {
                // 如果uri中包含不过滤的uri，则不进行过滤
                doFilter = false;
                break;
            }
        }

        if (doFilter && request.getSession().getAttribute(AdminController.SESSION_ADMIN_USER) == null)
        {
            if (request.getHeader("X-Requested-With") != null &&
                request.getHeader("X-Requested-With").equals("XMLHttpRequest"))
            {
                response.sendError(401, "session timeout");
            }
            else
            {
                response.sendRedirect(path + "/admin/index");
            }

        }
        else
        {
            filterChain.doFilter(request, response);
        }
    }
}